package 力扣;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @author yyq
 * @create 2022-04-07 9:52
 */
public class leetcode116 {
    public Node connect(Node root) {
        Queue<Node> queue=new LinkedList<>();
        int layerNodes = 1;
        if(root==null) return root;
        queue.add(root);
        while (!queue.isEmpty()){
            int temp=0;
            Node a = queue.peek(); //代表前一个
            while(layerNodes!=0){
                Node b = queue.poll();
                if(b.left!=null){
                    temp++;
                    queue.add(b.left);
                }
                if(b.right!=null){
                    temp++;
                    queue.add(b.right);
                }
                if(a!=b){
                    a.next = b;
                    a=b;
                }
                layerNodes--;
            }
            layerNodes=temp;
        }
        return root;
    }
}
class Node {
    public int val;
    public Node left;
    public Node right;
    public Node next;

    public Node() {}

    public Node(int _val) {
        val = _val;
    }

    public Node(int _val, Node _left, Node _right, Node _next) {
        val = _val;
        left = _left;
        right = _right;
        next = _next;
    }
};
